export class ProtocolParser {
    private _protocolMap: Map<number, Function> = new Map();

    registerProtocol(protocolId: number, handler: Function): void {
        this._protocolMap.set(protocolId, handler);
    }

    encode(protocolId: number, data: any): ArrayBuffer {
        const jsonStr = JSON.stringify(data);
        const encoder = new TextEncoder();
        const dataView = encoder.encode(jsonStr);

        const buffer = new ArrayBuffer(2 + dataView.length);
        const view = new DataView(buffer);

        view.setUint16(0, protocolId, true);
        for (let i = 0; i < dataView.length; i++) {
            view.setUint8(2 + i, dataView[i]);
        }

        return buffer;
    }

    decode(data: ArrayBuffer): { protocolId: number, payload: any, requestId?: number } {
        const view = new DataView(data);
        const protocolId = view.getUint16(0, true);

        const uint8Array = new Uint8Array(data.slice(2));
        const decoder = new TextDecoder();
        const jsonStr = decoder.decode(uint8Array);
        const payload = JSON.parse(jsonStr);

        let requestId;
        if (payload.__requestId) {
            requestId = payload.__requestId;
            delete payload.__requestId;
        }

        return { protocolId, payload, requestId };
    }
}
